package com.zy.smartdb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zy.smartdb.enums.ColumnType;
import com.zy.smartdb.pojo.AjaxResult;
import com.zy.smartdb.pojo.FieldDesc;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("json")
public class JsonController {

    //todo
    @PostMapping("/saveTemplate")
    public AjaxResult saveTemplate(@RequestBody String saveTemplate) {
        JSONObject json = (JSONObject) JSONObject.parse(saveTemplate);
        List<FieldDesc> list = getFields(json);
        JSONArray group = json.getJSONArray("group");
        for (int i = 0; i < group.size(); i++) {
            JSONObject gp = group.getJSONObject(i);
            list.addAll(getFields(gp));
        }
//        list.stream().map(e->e.getProp()).collect(Collectors.toSet()).forEach(System.out::println);
        return AjaxResult.success();
    }

    private List<FieldDesc> getFields(JSONObject json) {
        JSONArray column = json.getJSONArray("column");
        List<FieldDesc> list = new ArrayList<>();
        for (int i = 0; i < column.size(); i++) {
            JSONObject item = (JSONObject) column.get(i);
            FieldDesc fieldDesc = FieldDesc.builder()
                    .type(ColumnType.find(item.getString("type")))
                    .label(item.getString("label"))
                    .prop(item.getString("prop"))
                    .build();
            list.add(fieldDesc);
        }
        return list;
    }

}
